package com.atguigu.shirotest;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.realm.AuthenticatingRealm;
import org.apache.shiro.util.ByteSource;

/**
 * className: MyRealm
 * description:
 * date: 2024/6/17-21:02
 * <p>
 * project: shiro
 * package: com.atguigu.shirotest
 * email: 1085844536@qq.com
 * version:
 *
 * @author WangGuojian
 */
public class MyRealm extends AuthenticatingRealm {
    /**
     * 自定义登录认证方法，shiro 的 login 方法底层会调用该类的认证方法进行认证
     * 需要配置自定义的 realm 生效，在 ini 文件中配置，在 SpringBoot 中配置
     * 该方法只是获取进行对比的信息，认证逻辑还是按照 shiro 底层认证逻辑完成
     * <p>
     * Retrieves authentication data from an implementation-specific datasource (RDBMS, LDAP, etc) for the given
     * authentication token.
     * <p/>
     * For most datasources, this means just 'pulling' authentication data for an associated subject/user and nothing
     * more and letting Shiro do the rest.  But in some systems, this method could actually perform EIS specific
     * log-in logic in addition to just retrieving data - it is up to the Realm implementation.
     * <p/>
     * A {@code null} return value means that no account could be associated with the specified token.
     *
     * @param token the authentication token containing the user's principal and credentials.
     * @return an {@link AuthenticationInfo} object containing account data resulting from the
     * authentication ONLY if the lookup is successful (i.e. account exists and is valid, etc.)
     * @throws AuthenticationException if there is an error acquiring data or performing
     *                                 realm-specific authentication logic for the specified <tt>token</tt>
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        // 1.获取身份信息
        String principal = token.getPrincipal().toString();
        // 2.获取凭证信息
        String password = new String((char[]) token.getCredentials());
        System.out.println("认证用户信息：" + principal + "---" + password);

        // 3.获取数据库中存储的用户信息
        if (principal.equals("zhangsan")) {
            // 3.1.数据库中存储的加盐3次迭代的密码
            String pwdInfo = "7174f64b13022acd3c56e2781e098a5f";
            // 4.创建封装校验逻辑对象，封装数据返回
            return new SimpleAuthenticationInfo(
                    token.getPrincipal(),
                    pwdInfo,
                    ByteSource.Util.bytes("salt"),
                    principal
            );
        }
        // 4.创建封装校验逻辑对象，封装数据返回
        return null;
    }
}
